<script setup lang="ts">
import { getSts } from '@/service/common'
import { awaitTo } from '@/utils'
import { IOssModel } from '@/utils/upload/browserUpload'
import { getPolicyBase64, getSignature } from '@/utils/upload/miniAppUpload'
import { UploadFile } from 'wot-design-uni/components/wd-upload/types'

const props = withDefaults(
  defineProps<{
    modelValue: string[]
  }>(),
  {},
)

const fileList = ref<UploadFile[]>([])

// watchEffect(() => {
//   if (props.modelValue?.length) {
//     console.log(props.modelValue)

//     fileList.value = props.modelValue.map((url) => ({
//       url,
//     }))
//     console.log(fileList.value)
//   }
// })

const host = ref('')
const ossInfo = ref<IOssModel>({
  RequestId: '',
  Credentials: {
    AccessKeySecret: '',
    Expiration: '',
    AccessKeyId: '',
    SecurityToken: '',
  },
  AssumedRoleUser: {
    AssumedRoleId: '',
    Arn: '',
  },
  EndPoint: '',
  Bucket: '',
  OssUrl: '',
  path: '',
})

onMounted(async () => {
  const { result } = await awaitTo(getSts()) // 获取oss信息
  const _ossInfo = result.data
  host.value = `https://${_ossInfo.Bucket}.${_ossInfo.EndPoint}/`
  ossInfo.value = _ossInfo
})

const emit = defineEmits(['update:modelValue'])
/* *
 * 构建 formData
 * @param {Object} { file, formData, resolve }
 * @return {Object} formData
 * */
const buildFormData = async ({ file, formData, resolve }) => {
  let imageName = file.url.substring(file.url.lastIndexOf('/') + 1)
  // #ifdef H5
  imageName = imageName + file.name
  // #endif

  const aliyunFileKey = ossInfo.value.path + new Date().getTime() + imageName

  const accessid = ossInfo.value.Credentials.AccessKeyId
  const policyBase64 = getPolicyBase64(ossInfo.value.Credentials.Expiration)
  const signature = getSignature(policyBase64, ossInfo.value.Credentials.AccessKeySecret)

  formData = {
    ...formData,
    key: aliyunFileKey,
    policy: policyBase64,
    OSSAccessKeyId: accessid,
    'x-oss-security-token': ossInfo.value.Credentials.SecurityToken,
    signature,
    success_action_status: '200',
  }
  resolve(formData)
}

function handleChange({
  file,
  fileList,
  formData,
}: {
  file: UploadFile
  fileList: UploadFile[]
  formData: any
}) {
  const url = host.value + formData.key
  fileList.forEach((item) => {
    if (item.uid === file.uid) {
      item.url = url
    }
  })
  const urlList = fileList.map((item) => item.url)
  emit('update:modelValue', urlList)
}
</script>

<template>
  <view class="use-upload">
    <wd-upload
      v-bind="$attrs"
      :action="host"
      v-model:file-list="fileList"
      :build-form-data="buildFormData"
      @success="handleChange"
    >
      <image class="upload-btn" src="@/static/images/comment/add-picture-icon.png"></image>
    </wd-upload>
  </view>
</template>

<style lang="scss" scoped>
.upload-btn {
  width: 188rpx;
  height: 188rpx;
  background-color: #f7f8fa;
  border-radius: 20rpx;
}
</style>
